const fs = require("fs");
const puppeteer = require("puppeteer");
const download = require("download");

(async () => {
  // 1. 打开浏览器
  const browser = await puppeteer.launch({
    headless: false,
  });
  // 2. 新建标签页
  const page = await browser.newPage();
  // 3. 输入网址 & 等待网址加载完成
  await page.goto("https://movie.douban.com/cinema/nowplaying/beijing/", {
    waitUntil: "networkidle2", // 等待页面资源剩2个以下没有加载的时候就算完成了
  });
  // 4. 执行脚本爬取数据
  const result = await page.evaluate(() => {
    // 爬取网址的数据，并返回
    const liList = Array.from(document.querySelectorAll(".list-item"));
    return liList.map((liEl) => {
      const { title, score, subject } = liEl.dataset;
      const poster = liEl.querySelector("img").src;
      return {
        id: subject,
        title: title,
        score: score,
        poster: poster,
      };
    });
  });

  result.forEach((movie) => {
    download(movie.poster, "public");
    // https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2905021483.webp
    const names = movie.poster.split("/");
    movie.poster = names[names.length - 1];
  });

  fs.writeFileSync("movies.json", JSON.stringify(result));
  // 5. 关闭浏览器
  await browser.close();
})();
